﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System.Windows;
using ToDoIt2.Model.Persistent.UI;
using System.Collections.ObjectModel;
using ToDoIt2.Model.Persistent;
using ToDoIt2.Aspects;
using MonitoredUndo;
using System.Diagnostics;

namespace ToDoIt2.Model {
	[NotifyPropertyChanged]
	public class Document : pklib.DataObject {
		protected App App { get { return (App.Current as App); } }
		protected FluentConfiguration FluentConfig { get { return this.App.FluentConfig; } }

		public ISessionFactory SessionFactory { get; private set; }
		public ObservableCollection<TabPrefs>	Tabs { get; set; }

		private string Filepath = "";

		private Item _RootItem = new Item();
		public Item RootItem { get { return this._RootItem; } set { this._RootItem = value; } }

		/*******************************************************************/

		public Document() {
			this.FluentConfig
				.Database(SQLiteConfiguration.Standard.InMemory);
			this.Tabs = new ObservableCollection<TabPrefs>();
			this.Initialize();
		}

		public Document(string Filepath) {
			this.Filepath = Filepath;
			this.FluentConfig
				.Database(SQLiteConfiguration.Standard.UsingFile(this.Filepath));
			this.Initialize();
		}

		public TabPrefs CreateTab() {
			var NewTab = new TabPrefs();
			this.Tabs.Add(NewTab);
			return NewTab;
		}

		public void RemoveTab(TabPrefs tp) {
			this.Tabs.Remove(tp);
		}

		private void Initialize() {
			this.App.DisplayException(delegate {
				this.SessionFactory = this.FluentConfig.BuildSessionFactory();
				String Changes = "";
				new SchemaUpdate((App.Current as App).FluentConfig.BuildConfiguration())
					.Execute(delegate(string x) {
					Changes += x;
				}, true);
#if DEBUG
				if (Changes.Length > 0 && this.Filepath != "")
					MessageBox.Show("Schema Was Updated With: " + Changes);
#endif
#if DEBUG
				if (this.Filepath == "") {	// Then Insert Some Data
					/*		Test Folder
					 *			Test Project
					 *				Test Sub-Project 1
					 *		Test Folder 2
					 *			Test Project 2
					 */
					var	TF		= new Folder("Test Folder");
					var	TP		= new Folder("Test Project");
					var	TSP1	= new Folder("Test Sub-Project 1");
					var	TF2		= new Folder("Test Folder 2");
					var	TP2		= new Folder("Test Project 2");

					TP.Children.Add(TSP1);
					TF2.Children.Add(TP2);
					TF.Children.Add(TP);
					this.RootItem.Children.Add(TF);
					this.RootItem.Children.Add(TF2);
				}
#endif
			});
		}

		internal static void ShowSchema() {
			#if DEBUG
				String Schema = "";
				new SchemaExport((App.Current as App).FluentConfig.BuildConfiguration())
					.Execute(delegate(string x) {
						Schema += x;
					}, false, false);
				MessageBox.Show(Schema);
			#endif
		}
	}
}
